<?php

namespace Home\Controller;

use Common\Api_51;
use Common\Api_Ins;
use Common\Top;
use Common\Utils;
use Common\STD3Des;
use Common\XmlToArray;
use Think\Controller;
use Common\Sms;

class TestController extends CommonController
{
    /**
     * 获取1级区域
     */
    public function index()
    {
        $url = $this->ticketUrl() . 'Agent_GetRegionList';
        $_pid = $this->ticketPid();
        $_ts = time();
        $parentregioncode = '310000';
        $_sign = "_pid=$_pid&_ts=$_ts&format=xml" . $this->secretKey();
        $_sign = md5($_sign);
        $data = "_pid=$_pid&format=xml&_ts=$_ts&_sign=$_sign";
        $result = Utils::vpost($url, $data);

        //返回xml数据
        $list = $this->xml_to_array($result);
        $bodyContent = implode('', $list['Body']);
        //实例化
        $list = $this->des($bodyContent);

        $list = $list['API_Region'];
        foreach ($list as $k => $v) {
            $list['code'] = $v['RegionCode'];
            $list['name'] = $v['RegionName'];
            $list['level'] = $v['RegionLevel'];
            M('region')->add($list);
        }
    }


    /**
     * 获取2级区域
     */
    public function addCity()
    {
        $list = M('region')->where("level = 1")->select();
        foreach ($list as $k => $v) {
            $url = $this->ticketUrl() . 'Agent_GetRegionList';
            $_pid = $this->ticketPid();
            $_ts = time();
            $parentregioncode = $v['code'];
            $_sign = "_pid=$_pid&_ts=$_ts&format=xml&parentregioncode=$parentregioncode" . $this->secretKey();
            $_sign = md5($_sign);
            $data = "_pid=$_pid&format=xml&parentregioncode=$parentregioncode&_ts=$_ts&_sign=$_sign";
            $result = Utils::vpost($url, $data);
            //返回xml数据
            $list = $this->xml_to_array($result);

            if ($list['Head']['Message'] == 'success' && $list['Head']['Result'] == 'true' && $list['Head']['StatusCode'] == '100') {
                $bodyContent = implode('', $list['Body']);
                //实例化
                $list = $this->des($bodyContent);
                $list = $list['API_Region'];

                if (empty($list[0])) {
                    $arr[0] = $list;
                } else {
                    $arr = $list;
                }

                foreach ($arr as $key => $value) {
                    $list['code'] = $value['RegionCode'];
                    $list['name'] = $value['RegionName'];
                    $list['level'] = $value['RegionLevel'];
                    M('region')->add($list);
                }
            }
        }
    }


    public function getProductHeadInfo($code)
    {
        $url = $this->ticketUrl() . 'Agent_GetProductList';
        $_pid = $this->ticketPid();
        $_ts = time();
        $pageindex = 1;
        $pagesize = 20;
        $regioncode = $code;
        $_sign = "_pid=$_pid&_ts=$_ts&format=xml&pageindex=$pageindex&pagesize=$pagesize&regioncode=$regioncode" . $this->secretKey();
        $_sign = md5($_sign);
        $data = "_pid=$_pid&_ts=$_ts&format=xml&pageindex=$pageindex&pagesize=$pagesize&regioncode=$regioncode&_sign=$_sign";
        $result = Utils::vpost($url, $data);
        //返回xml数据
        $list = $this->xml_to_array($result);
        $list = $list['Head'];
        return $list;
    }


    /**
     * 详情
     */
    public function getProductList()
    {
        $codeList = M('region')->where("level = 2")->select();
        foreach ($codeList as $k => $v) {

            $productHeadInfo = $this->getProductHeadInfo($v['code']);
            $records = $productHeadInfo['Reconds'];

            if ($productHeadInfo['Result'] == 'true' && $productHeadInfo['StatusCode'] == '100' && $productHeadInfo['Message'] == 'success') {
                $sum = (int)ceil($records / 20);

                for ($i = 1; $i <= $sum; $i++) {
                    $url = $this->ticketUrl() . 'Agent_GetProductList';
                    $_pid = $this->ticketPid();
                    $_ts = time();
                    $pageindex = $i;
                    $pagesize = 20;
                    $regioncode = $v['code'];
                    $_sign = "_pid=$_pid&_ts=$_ts&format=xml&pageindex=$pageindex&pagesize=$pagesize&regioncode=$regioncode" . $this->secretKey();
                    $_sign = md5($_sign);
                    $data = "_pid=$_pid&_ts=$_ts&format=xml&pageindex=$pageindex&pagesize=$pagesize&regioncode=$regioncode&_sign=$_sign";
                    $result = Utils::vpost($url, $data);
                    //返回xml数据
                    $list = $this->xml_to_array($result);
                    $bodyContent = implode('', $list['Body']);

                    //实例化
                    $rep = new STD3Des ();
                    $arr = $rep->decrypt($bodyContent);
                    $arr = $this->xml2array($arr);

                    //得到二维数组
                    $productList = $arr['ArrayOfAPI_Product']['API_Product'];

                    if (!$productList[0]) {
                        $productListArray[0] = $productList;
                    } else {
                        $productListArray = $productList;
                    }


                    foreach ($productListArray as $key => $value) {
                        $info['code'] = $v['code'];
                        $info['product_name'] = $value['ProductName'];
                        $info['name'] = $value['SightName'];
                        $info['supplier_level'] = $value['SupplierLevel'];
                        $info['auto_cancel_time'] = $value['AutoCancelTime'];
                        $info['book_advance_day'] = $value['BookAdvanceDay'];
                        $info['buy_max_num'] = $value['BuyMaxNum'];
                        $info['buy_min_num'] = $value['BuyMinNum'];
                        $info['can_refund'] = $value['CanRefund'];
                        $info['city'] = $value['City'];
                        $info['credentials_required'] = $value['CredentialsRequired'];
                        $info['certificate_type'] = $value['CertificateType'];
                        $info['days_after_use_date_valid'] = $value['DaysAfterUseDateValid'];
                        $info['fee_include'] = $value['FeeInclude'];
                        $info['imgs'] = $value['Imgs'];
                        $info['is_real_name'] = $value['IsRealName'];
                        $info['key_id'] = $value['KeyId'];
                        $info['supplier_key_id'] = $value['SupplierKeyId'];
                        $info['market_price'] = $value['MarketPrice'];
                        $info['sell_price'] = $value['SellPrice'];
                        $info['settle_price'] = $value['SettlementPrice'];
                        $info['stock'] = $value['Sellstock'];
                        $info['period_validity_of_refund'] = $value['PeriodValidityOfRefund'];
                        $info['quantity_min_purchase'] = $value['QuantityLimitedToPurchase'];
                        $info['refund_fee'] = $value['RefundCharge'];
                        $info['refund_info'] = $value['RefundInfo'];
                        $info['remind'] = $value['Remind'];
                        $info['state'] = $value['Status'];
                        $info['ticket_category'] = $value['TicketCategory'];
                        $info['time_zone'] = $value['TimeZone'];
                        $info['use_advance_hour'] = $value['UseAdvanceHour'];
                        $info['valid_week'] = $value['ValidWeek'];
                        $info['create_time'] = date("Y-m-d H:i:s", time());
                        M('ticket')->add($info);
                    }
                }
            }
        }
    }


    public function updateScenicInfo()
    {
        $codeList = M('ticket')->field('id,supplier_key_id')->where("supplier_key_id != ''")->select();

        foreach ($codeList as $k => $v) {
            $scenicInfo = $this->getScenicList($v['supplier_key_id']);

            if ($scenicInfo != '10004') {
                $supplierKeyId = $v['SupplierKeyId'];
                $scenicInfo['address'] = $scenicInfo['SightAddress'];
                $scenicInfo['category'] = $scenicInfo['SightBusinessCategory'];
                $scenicInfo['lat'] = $scenicInfo['Sightlat'];
                $scenicInfo['lon'] = $scenicInfo['Sightlon'];
                $scenicInfo['introduction'] = $scenicInfo['SightIntroduction'];
                $scenicInfo['bus_info'] = $scenicInfo['SightBusInfo'];
                $scenicInfo['car_lines'] = $scenicInfo['SightCarLines'];
                $scenicInfo['phone'] = $scenicInfo['Telephone'];

                M('ticket')->where("supplier_key_id = '{$supplierKeyId}'")->save($scenicInfo);
            }
        }
    }

    public function test()
    {
        $app_id = "101370092";
        //应用的APPKEY
        $app_secret = "74ff18d23b0d9d8a3ed8ae46d3ecf402";
        //成功授权后的回调地址
        $my_url = "http://zhangda.m.lydlr.com/index.php/Home/Test/test";

        $url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=$app_id&redirect_uri=$my_url&scope=get_user_info";

        Header("Location:" . $url);
    }


    function getFirstCharter($str)
    {
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284) return 'a';
        if ($asc >= -20283 && $asc <= -19776) return 'b';
        if ($asc >= -19775 && $asc <= -19219) return 'c';
        if ($asc >= -19218 && $asc <= -18711) return 'd';
        if ($asc >= -18710 && $asc <= -18527) return 'e';
        if ($asc >= -18526 && $asc <= -18240) return 'f';
        if ($asc >= -18239 && $asc <= -17923) return 'g';
        if ($asc >= -17922 && $asc <= -17418) return 'h';
        if ($asc >= -17417 && $asc <= -16475) return 'j';
        if ($asc >= -16474 && $asc <= -16213) return 'k';
        if ($asc >= -16212 && $asc <= -15641) return 'l';
        if ($asc >= -15640 && $asc <= -15166) return 'm';
        if ($asc >= -15165 && $asc <= -14923) return 'n';
        if ($asc >= -14922 && $asc <= -14915) return 'o';
        if ($asc >= -14914 && $asc <= -14631) return 'p';
        if ($asc >= -14630 && $asc <= -14150) return 'q';
        if ($asc >= -14149 && $asc <= -14091) return 'r';
        if ($asc >= -14090 && $asc <= -13319) return 's';
        if ($asc >= -13318 && $asc <= -12839) return 't';
        if ($asc >= -12838 && $asc <= -12557) return 'w';
        if ($asc >= -12556 && $asc <= -11848) return 'x';
        if ($asc >= -11847 && $asc <= -11056) return 'y';
        if ($asc >= -11055 && $asc <= -10247) return 'z';
        return null;
    }


    /**
     * 获取景区信息列表
     */
    public function getScenicList($code)
    {
        $url = $this->ticketUrl() . 'Agent_GetScenicInfoByKeyId';
        $_pid = $this->ticketPid();
        $_ts = time();
        //$pageindex = $i;
        //$pagesize = 20;
        $id = $code;
        $_sign = "_pid=$_pid&_ts=$_ts&format=xml&id=$id" . $this->secretKey();
        $_sign = md5($_sign);
        $data = "_pid=$_pid&_ts=$_ts&format=xml&id=$id&_sign=$_sign";
        $result = Utils::vpost($url, $data);

        //返回xml数据
        $list = $this->xml_to_array($result);

        if ($list['Head']['StatusCode'] != 100 || $list['Head']['Message'] != '成功') {
            $scenicList = 10004;
            return $scenicList;
        } else {
            $bodyContent = implode('', $list['Body']);

            //实例化
            $rep = new STD3Des ();
            $arr = $rep->decrypt($bodyContent);
            $arr = $this->xml2array($arr);

            //得到二维数组
            $scenicList = $arr['API_Scenic'];
            return $scenicList;
        }
    }


    function des($bodyContent)
    {
        $rep = new STD3Des ();
        $list = $rep->decrypt($bodyContent);
        $list = $this->xml_to_array($list);
        return $list;
    }


    /**
     * xml to array
     */
    function xml2array($contents, $get_attributes = 1, $priority = 'tag')
    {
        if (!$contents) return array();
        if (!function_exists('xml_parser_create')) {
            //print "'xml_parser_create()' function not found!";
            return array();
        }
        //Get the XML parser of PHP - PHP must have this module for the parser to work
        $parser = xml_parser_create('');
        xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
        xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
        xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parse_into_struct($parser, trim($contents), $xml_values);
        xml_parser_free($parser);
        if (!$xml_values) return;//Hmm...
        //Initializations
        $xml_array = array();
        $parents = array();
        $opened_tags = array();
        $arr = array();
        $current = &$xml_array; //Refference
        //Go through the tags.
        $repeated_tag_index = array();//Multiple tags with same name will be turned into an array
        foreach ($xml_values as $data) {
            unset($attributes, $value);//Remove existing values, or there will be trouble
            //This command will extract these variables into the foreach scope
            // tag(string), type(string), level(int), attributes(array).
            extract($data);//We could use the array by itself, but this cooler.
            $result = array();
            $attributes_data = array();

            if (isset($value)) {
                if ($priority == 'tag') $result = $value;
                else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
            }
            //Set the attributes too.
            if (isset($attributes) and $get_attributes) {
                foreach ($attributes as $attr => $val) {
                    if ($priority == 'tag') $attributes_data[$attr] = $val;
                    else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
                }
            }
            //See tag status and do the needed.
            if ($type == "open") {//The starting of the tag '<tag>'
                $parent[$level - 1] = &$current;
                if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                    $current[$tag] = $result;
                    if ($attributes_data) $current[$tag . '_attr'] = $attributes_data;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    $current = &$current[$tag];
                } else { //There was another element with the same tag name
                    if (isset($current[$tag][0])) {//If there is a 0th element it is already an array
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
                        $repeated_tag_index[$tag . '_' . $level]++;
                    } else {//This section will make the value an array if multiple tags with the same name appear together
                        $current[$tag] = array($current[$tag], $result);//This will combine the existing item and the new item together to make an array
                        $repeated_tag_index[$tag . '_' . $level] = 2;

                        if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                            unset($current[$tag . '_attr']);
                        }
                    }
                    $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
                    $current = &$current[$tag][$last_item_index];
                }
            } elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
                //See if the key is already taken.
                if (!isset($current[$tag])) { //New Key
                    $current[$tag] = $result;
                    $repeated_tag_index[$tag . '_' . $level] = 1;
                    if ($priority == 'tag' and $attributes_data) $current[$tag . '_attr'] = $attributes_data;
                } else { //If taken, put all things inside a list(array)
                    if (isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...
                        // ...push the new element into that array.
                        $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;

                        if ($priority == 'tag' and $get_attributes and $attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                        }
                        $repeated_tag_index[$tag . '_' . $level]++;
                    } else { //If it is not an array...
                        $current[$tag] = array($current[$tag], $result); //...Make it an array using using the existing value and the new value
                        $repeated_tag_index[$tag . '_' . $level] = 1;
                        if ($priority == 'tag' and $get_attributes) {
                            if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well

                                $current[$tag]['0_attr'] = $current[$tag . '_attr'];
                                unset($current[$tag . '_attr']);
                            }

                            if ($attributes_data) {
                                $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
                            }
                        }
                        $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
                    }
                }
            } elseif ($type == 'close') { //End of tag '</tag>'
                $current = &$parent[$level - 1];
            }
        }

        return ($xml_array);
    }


}
